package org.snail.proxy.server;

import org.snail.proxy.server.netty.NettyServer;
import org.snail.proxy.server.netty.ProxyClientServer;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.util.concurrent.CountDownLatch;

@Component
public class InitRunner implements ApplicationRunner {
	private final ProxyClientServer proxyClientServer;

	public InitRunner(ProxyClientServer proxyClientServer) {
		this.proxyClientServer = proxyClientServer;
	}

	/**
     * 在服务启动完成（特指SpringApplication）后立即执行
     */
    @Override
    @Async
    public void run(ApplicationArguments args) {
        initServer();
    }
    
	/**
	 * 初始化TCP服务
	 */
	private void initServer() {
		final CountDownLatch waiter = new CountDownLatch(2);
		startServer(proxyClientServer, waiter);
		try {
			// 等待服务成功启动。再继续后面的逻辑
			waiter.await();
		} catch (InterruptedException e) {
//			DLog.LOG_STDOUT_SYNC.error("", e);
			e.printStackTrace();
		}
	}

	public static void startServer(NettyServer server, CountDownLatch waiter) {
		server.start(future -> {
			if (future.isSuccess()) {
			} else {
				System.exit(1);
			}
			waiter.countDown();
		}, future -> {
			if (future.isSuccess()) {
			} else {
				System.exit(1);
			}
			waiter.countDown();
		}, () -> {
		});
	}
}
